import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '../stores/user';
import MerchantLayout from '../layouts/MerchantLayout.vue';
import UserLayout from '../layouts/UserLayout.vue';

// Route definitions
const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: { requiresAuth: false },
    beforeEnter: (to, from, next) => {
      const userStore = useUserStore();
      
      // 如果用户已登录，根据角色自动重定向到对应页面
      if (userStore.isLoggedIn) {
        if (userStore.isMerchant) {
          next({ name: 'MerchantDashboard' });
        } else {
          next({ name: 'UserHome' });
        }
      } else {
        next();
      }
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/merchant/login',
    name: 'MerchantLogin',
    component: () => import('../views/merchant/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/merchant/register',
    name: 'MerchantRegister',
    component: () => import('../views/merchant/Register.vue'),
    meta: { requiresAuth: false }
  },
  // 使用布局组件的用户路由
  {
    path: '/user',
    component: UserLayout,
    meta: { requiresAuth: true, isMerchant: false },
    children: [
      {
        path: 'home',
        name: 'UserHome',
        component: () => import('../views/user/HomePage.vue')
      },
      {
        path: 'products',
        name: 'UserProducts',
        component: () => import('../views/user/ProductList.vue')
      },
      {
        path: 'product/:id',
        name: 'UserProductDetail',
        component: () => import('../views/user/ProductDetail.vue')
      },
      {
        path: 'orders',
        name: 'UserOrders',
        component: () => import('../views/user/OrderList.vue')
      },
      {
        path: 'order/confirm',
        name: 'OrderConfirm',
        component: () => import('../views/user/order/OrderConfirm.vue')
      },
      {
        path: 'payment/:orderId',
        name: 'OrderPayment',
        component: () => import('../views/user/payment/PaymentPage.vue')
      },
      {
        path: 'payment/result',
        name: 'PaymentResult',
        component: () => import('../views/user/payment/PaymentResult.vue')
      },
      {
        path: '', // 默认子路由
        redirect: '/user/home'
      }
    ]
  },
  // 使用布局组件的商家路由
  {
    path: '/merchant',
    component: MerchantLayout,
    meta: { requiresAuth: true, isMerchant: true },
    children: [
      {
        path: 'dashboard',
        name: 'MerchantDashboard',
        component: () => import('../views/merchant/Dashboard.vue')
      },
      {
        path: 'orders',
        name: 'MerchantOrders',
        component: () => import('../views/merchant/Orders.vue')
      },
      {
        path: 'products',
        name: 'MerchantProducts',
        component: () => import('../views/merchant/Products.vue')
      },
      {
        path: 'inventory',
        name: 'MerchantInventory',
        component: () => import('../views/merchant/Inventory.vue')
      },
      {
        path: 'logistics',
        name: 'MerchantLogistics',
        component: () => import('../views/merchant/Logistics.vue')
      },
      {
        path: 'customers',
        name: 'MerchantCustomers',
        component: () => import('../views/merchant/Customers.vue')
      },
      {
        path: 'analytics',
        name: 'MerchantAnalytics',
        component: () => import('../views/merchant/Analytics.vue')
      },
      {
        path: 'settings',
        name: 'MerchantSettings',
        component: () => import('../views/merchant/Settings.vue')
      },
      {
        path: '', // 默认子路由
        redirect: '/merchant/dashboard'
      }
    ]
  },
  // 保留原来的首页路由，重定向到对应主页
  {
    path: '/merchant/home',
    name: 'MerchantHome',
    redirect: '/merchant/dashboard'
  }
];

// Create router instance
const router = createRouter({
  history: createWebHistory(),
  routes
});

// Navigation guard - Check user login status and permissions
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  const requiresAuth = to.meta.requiresAuth;
  const isMerchantPage = to.meta.isMerchant;
  
  // 如果尝试访问登录页但已经登录，重定向到对应的主页
  if ((to.name === 'Login' || to.name === 'MerchantLogin') && userStore.isLoggedIn) {
    if (userStore.isMerchant) {
      next({ name: 'MerchantDashboard' });
    } else {
      next({ name: 'UserHome' });
    }
    return;
  }
  
  // If page requires login
  if (requiresAuth) {
    // If user is not logged in, redirect to login page
    if (!userStore.isLoggedIn) {
      next({ name: userStore.isMerchant ? 'MerchantLogin' : 'Login' });
      return;
    }
    
    // If it's a merchant page but user is not a merchant, or it's a user page but user is a merchant
    if ((isMerchantPage && !userStore.isMerchant) || 
        (!isMerchantPage && userStore.isMerchant)) {
      // Choose appropriate homepage based on user type
      next({ name: userStore.isMerchant ? 'MerchantDashboard' : 'UserHome' });
      return;
    }
  }
  
  // Default allow access
  next();
});

export default router;